package com.minelx.sqlstructures.core;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

public enum ColumnType {
	INT() {
		@Override
		public String cellAsText0(ResultSet resultSet, int cellAt) throws SQLException {
			return String.valueOf(resultSet.getInt(cellAt));
		}

		@Override
		public String representAsSql(String content) {
			return content;
		}
	},
	TEXT() {
		@Override
		public String cellAsText0(ResultSet resultSet, int cellAt) throws SQLException {
			return resultSet.getString(cellAt);
		}

		@Override
		public String representAsSql(String content) {
			return '"' + content + '"';
		}
	},
	DECIMAL() {
		@Override
		public String cellAsText0(ResultSet resultSet, int cellAt) throws SQLException {
			return String.valueOf(resultSet.getBigDecimal(cellAt));
		}

		@Override
		public String representAsSql(String content) {
			return content;
		}
	};

	abstract String cellAsText0(ResultSet resultSet, int cellAt) throws SQLException;

	public abstract String representAsSql(String content);

	public String cellAsText(ResultSet resultSet, int cellAt) {
		try {
			return cellAsText0(resultSet, cellAt);
		} catch (SQLException e) {
			throw new RuntimeException("error while getting value from result set.", e);
		}
	}

	public static ColumnType from(int columnType) {
		if (Types.INTEGER == columnType || Types.BIGINT == columnType || Types.TINYINT == columnType) {
			return INT;
		} else if (Types.DECIMAL == columnType || Types.FLOAT == columnType) {
			return DECIMAL;
		} else if (Types.VARCHAR == columnType || Types.CHAR == columnType) {
			return TEXT;
		} else {
			throw new IllegalStateException("can't recognize sql type: " + columnType);
		}
	}

	public static ColumnType from(String typeName) {
		if (typeName.contains("int")) {
			return INT;
		} else if (typeName.contains("varchar") || typeName.contains("char")) {
			return TEXT;
		} else if (typeName.contains("decimal")) {
			return DECIMAL;
		} else if (typeName.equals("float")) {
			return DECIMAL;
		} else if (typeName.equals("double")) {
			return DECIMAL;
		}
		throw new IllegalArgumentException("unexpected type name: " + typeName);
	}
}
